var app = getApp()

Page({
  data: {
    userInfo: {},
    isShowUserInfo: false,//显示用户信息——授权按钮
    canIUseGetUserProfile:false,//判断调试基础库版本——基础库 2.10.4 开始支持，低版本需做兼容处理。
    name:"",  //填写的姓名
    phone:"",  //填写的手机号
    isEmpty:false,  //是否显示姓名/手机号
    now_temp:"",  //气温
    now_icon:"",  //天气图标
    now_text:"",  //天气
    location:"",  //纬，经度
    hasLocation:false, //是否获取到位置
    city:"",  //城市信息
    isShow:false,  //是否显示上车信息
    start_station:"",  //上车地点
    date:"",  //日期
    start_time:"",  //上车时间
    Bus:"",  //车辆信息
  },

  onLoad: function() {
    var that = this
    if (wx.getUserProfile) {
      that.setData({
        canIUseGetUserProfile: true
      })
    }

    //加载填写的个人信息
    var name = wx.getStorageSync("nameKey")
    var phone = wx.getStorageSync("phoneKey")
    if(name != '' && phone != ''){
      that.setData({
          name:wx.getStorageSync("nameKey"),
          phone:wx.getStorageSync("phoneKey"),
          isEmpty:true
      })
    }

    //加载上车信息
    var station = wx.getStorageSync('station1Key')
    var date1 = wx.getStorageSync("dateKey")
    var time = wx.getStorageSync('time1Key')
    var bus = wx.getStorageSync("busKey")
    if(station != '' && date1 != '' && time != ''){
      that.setData({
        start_station:station,
        date:date1,
        start_time:time,
        Bus:bus,
        isShow:true
      })
    }

    //判断是否已授权
    var user = wx.getStorageSync('userKey'); //从本地缓存获取用户信息
    if(user && user.nickName){  //如果本地缓存有信息就显示本地缓存
      that.setData({
          userInfo:user,
          isShowUserInfo: true
      })
    }
  },
  
  //自定义函数
  //天气
  getWeather:function(){
    var that = this
    wx.request({
        url: 'https://devapi.qweather.com/v7/weather/now?',
        data:{
          location:that.data.location,
          key:'da81385b4ba34fc0a50b304734e0b635'
        },
        success:function(res){
          //console.log(res.data.now)
          that.setData({
            now_temp:res.data.now.temp.toString()+"℃",
            now_icon:res.data.now.icon,
            now_text:res.data.now.text
          })
        }
    });
  },

  //位置 —— 城市信息
  getLocation:function(){
    var that = this
    wx.request({
      url:'https://geoapi.qweather.com/v2/city/lookup?',
      data:{
        location:that.data.location,
        key:'da81385b4ba34fc0a50b304734e0b635'
      },
      success:function(res){
        //console.log(res.data.location[0])
        var City = res.data.location[0].adm2.toString() + "," + res.data.location[0].name.toString()  //拼接为字符串类型
        that.setData({
            city:City
        })
      }
    })
  },

  onShow:function(){
    var that = this
    // type: 'gcj02',//默认wgs84
    wx.getLocation({
      success: function(res){
        //console.log(res.latitude,res.longitude)//纬度，经度
        var locat = res.longitude.toString() + "," + res.latitude.toString()
        //console.log(locat);  //拼接为字符串类型
        that.data.location = locat  //同步 —— 在js文件中传输
        that.setData({
          hasLocation : true
        })  //异步 —— 显示在页面
        that.getWeather()
        that.getLocation()
      }
    })
  },

  //获取微信用户信息
  getUserProfile: function(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料',//不写不弹提示框
      success: (res) => {
          // console.log("用户的信息如下：" , res.userInfo);
          // wx.login({
          //     success: res => {
          //         // 获取到用户的 code 之后：res.code
          //         console.log("用户的code：" + res.code);
          //     }
          // });
          
          //调用云函数，获取用户openid
          wx.cloud.callFunction({
            name:"login",
            success:res=>{
              // console.log(res.result.openid)
              wx.setStorageSync('openidKey', res.result.openid);//存储openid 
            }
          })

          let user = res.userInfo
          wx.setStorageSync('userKey',user)
          this.setData({
              userInfo: user,
              isShowUserInfo: true
          })
      },
      fail: (res) => {
        wx.showModal({
          title: '提示',
          content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!',
          showCancel: false,
          confirmText: '返回授权',
          success: function(res) {
              // 用户没有授权成功，不需要改变 hasUserInfo 的值
              // if (res.confirm) {
              //     console.log('用户点击了“返回授权”');
              // }
          }
        });
      }
    })
  },

  //跳转乘车页面
  goToInformation:function(){
    var that = this;
    if(that.data.isEmpty){
      wx.getSetting({
        success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true){
            //未授权
            wx.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                if (res.confirm) {
                  //确定授权，通过wx.openSetting发起授权请求
                  wx.openSetting({
                    success: function (res) {
                      if (res.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                      } else {
                        wx.showToast({
                          title: '定位失败',
                          content: '请检查是否开启授权',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
          }else {
            // console.log('授权成功')
            wx.reLaunch({
                url: '/pages/information/information',
            });
          }
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '未完善个人信息，是否前往个人信息页面',
        showCancel: true,
        cancelText:'取消',
        confirmText: '确认',
        success: function(res) {
          if (res.confirm) {
            //console.log('用户点击确定')
            wx.navigateTo({
              url:'/pages/input/input'
            });
          }
        }
      });
    }
  },

  //跳转——乘车记录页面
  goToShow:function(){
    var that = this;
    if(that.data.isEmpty){
      wx.navigateTo({
        url: '/pages/show/show',
      });
    }else{
      wx.showModal({
        title: '提示',
        content: '未完善个人信息，是否前往个人信息页面',
        showCancel: true,
        cancelText:'取消',
        confirmText: '确认',
        success: function(res) {
            if (res.confirm) {
              //console.log('用户点击确定')
              wx.navigateTo({
                  url:'/pages/input/input',
              });
            }
        }
      });
    }
  }
})